package com.dura.api.filter.impl;

import com.dura.api.client.BeaconCacheClient;
import com.dura.common.enums.ExceptionEnums;
import com.dura.common.exception.ApiException;
import com.dura.api.filter.CheckFilter;
import com.dura.common.constant.CacheConstant;
import com.dura.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 校验请求的ip地址是否是白名单
 *
 * @version 1.0
 * @Author 振鹏
 * @Date 2025/3/15 9:49
 * @注释
 */
@Service(value = "ip")
@Slf4j
public class IPCheckFilter implements CheckFilter {


    @Autowired
    private BeaconCacheClient cacheClient;

    /**
     * 魔法
     */
    private final String IP_ADDRESS = "ipAddress";

    @Override
    public void check(StandardSubmit submit) {
        log.info("【接口模块-校验ip】   校验ing…………");
        List<String> ip = (List<String>) (cacheClient.hget(CacheConstant.CLIENT_BUSINESS + submit.getApikey(), IP_ADDRESS));
        submit.setIp(ip);

        if ((ip == null || ip.size() == 0) || ip.contains(submit.getRealIP())) {
            log.info("【接口模块-校验ip】  客户端请求IP合法！");
            return;
        }

        // IP 白名单不为空，并且客户端请求的ip不在名单内。
        log.info("【接口模块-校验ip】  客户端请求IP不在白名单内！");
        throw new ApiException(ExceptionEnums.IP_NOT_WHITE);
    }
}
